package com.nexus.plugin.security.filter;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.nexus.core.exception.AuthenicException;
import com.nexus.core.utils.ObjectUtils;
import com.nexus.core.utils.ResponseUtils;
import com.nexus.plugin.security.SecurityUtils;
import com.nexus.plugin.security.utils.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token验证过滤器
 *
 * @Date 2025/7/31 16:24
 * @Author luzhengning
 **/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取Token
        String token = JwtTokenProvider.resolveToken(request);
        // Token为空直接放行
        if (ObjectUtils.isEmpty(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            //解析Token并设置Security上下文
            Authentication auth = SecurityUtils.setAuthentication(token);
        } catch (SignatureVerificationException e) {
            ResponseUtils.sendResponse(response, 401, null, "Token校验错误");
            return;
        } catch (AuthenicException e) {
            SecurityContextHolder.clearContext();
            ResponseUtils.sendResponse(response, 401, null, e.getMessage());
            return;
        }

        filterChain.doFilter(request, response);
    }
}
